/**
 * ToolListView.js
 * 
 * 负责工具列表下拉菜单和工具参数填写对话框。
 * 用户点击工具按钮时显示可用工具列表，选择工具后填写参数并执行。
 */

(function() {
    'use strict';

    class ToolListView {
        constructor(options = {}) {
            this.onExecute = options.onExecute; // 工具执行回调
            this.tools = []; // 工具列表
            this.dropdown = null; // 下拉菜单DOM
            this.isOpen = false;
            
            this._init();
        }

        /**
         * 初始化
         * @private
         */
        _init() {
            // 创建下拉菜单容器
            this._createDropdown();
            
            // 绑定工具按钮点击事件
            const toolBtn = document.getElementById('tool-list-button');
            if (toolBtn) {
                toolBtn.onclick = () => this.toggleDropdown();
            }

            // 点击其他地方关闭下拉菜单
            document.addEventListener('click', (e) => {
                if (this.isOpen && !e.target.closest('#tool-list-button') && !e.target.closest('.tool-dropdown')) {
                    this.closeDropdown();
                }
            });
        }

        /**
         * 创建下拉菜单容器
         * @private
         */
        _createDropdown() {
            this.dropdown = document.createElement('div');
            this.dropdown.className = 'tool-dropdown';
            this.dropdown.innerHTML = '<p class="tool-dropdown-empty">暂无可用工具</p>';
            
            // 插入到控制区域
            const controlArea = document.getElementById('control-area');
            if (controlArea) {
                controlArea.insertBefore(this.dropdown, controlArea.firstChild);
            }
        }

        /**
         * 切换下拉菜单显示状态
         */
        toggleDropdown() {
            if (this.isOpen) {
                this.closeDropdown();
            } else {
                this.openDropdown();
            }
        }

        /**
         * 打开下拉菜单
         */
        openDropdown() {
            if (!this.dropdown) return;
            this.dropdown.classList.add('show');
            this.isOpen = true;
        }

        /**
         * 关闭下拉菜单
         */
        closeDropdown() {
            if (!this.dropdown) return;
            this.dropdown.classList.remove('show');
            this.isOpen = false;
        }

        /**
         * 渲染工具列表
         * @param {Array} tools - 工具数组
         */
        renderList(tools) {
            this.tools = tools || [];
            
            if (!this.dropdown) return;

            // 如果没有工具
            if (this.tools.length === 0) {
                this.dropdown.innerHTML = '<p class="tool-dropdown-empty">暂无可用工具</p>';
                return;
            }

            // 渲染工具列表
            const listHtml = this.tools.map(tool => `
                <div class="tool-dropdown-item" data-tool-id="${tool.id}">
                    <div class="tool-item-header">
                        <span class="codicon codicon-${tool.icon || 'tools'}"></span>
                        <span class="tool-item-name">${tool.name}</span>
                    </div>
                    ${tool.description ? `<div class="tool-item-description">${tool.description}</div>` : ''}
                </div>
            `).join('');

            this.dropdown.innerHTML = listHtml;

            // 绑定点击事件
            this.dropdown.querySelectorAll('.tool-dropdown-item').forEach(item => {
                item.onclick = () => {
                    const toolId = item.dataset.toolId;
                    const tool = this.tools.find(t => t.id === toolId);
                    if (tool) {
                        this.closeDropdown();
                        this._handleToolSelect(tool);
                    }
                };
            });
        }

        /**
         * 处理工具选择
         * @private
         */
        _handleToolSelect(tool) {
            // 如果工具有参数，显示参数填写对话框
            if (tool.parameters && tool.parameters.length > 0) {
                this._showParameterDialog(tool);
            } else {
                // 没有参数，直接执行
                this._executeTool(tool.id, tool.name, {});
            }
        }

        /**
         * 显示工具参数填写对话框
         * @private
         */
        _showParameterDialog(tool) {
            // 生成参数表单HTML
            const formHtml = this._generateParameterForm(tool);

            // 创建对话框
            const dialog = new window.DialogComponent({
                title: `执行工具: ${tool.name}`,
                content: formHtml,
                width: '600px',
                buttons: [
                    {
                        text: '取消',
                        action: 'cancel'
                    },
                    {
                        text: '执行',
                        primary: true,
                        action: 'execute',
                        onClick: (dialogInstance) => {
                            const args = this._collectParameters(tool, dialogInstance);
                            
                            // 验证必填参数
                            const validation = this._validateParameters(tool, args);
                            if (!validation.valid) {
                                alert(validation.message);
                                return false; // 不关闭对话框
                            }

                            // 执行工具
                            this._executeTool(tool.id, tool.name, args);
                            return true; // 关闭对话框
                        }
                    }
                ]
            });

            dialog.show();
        }

        /**
         * 生成参数表单HTML
         * @private
         */
        _generateParameterForm(tool) {
            if (!tool.parameters || tool.parameters.length === 0) {
                return '<p>此工具无需参数</p>';
            }

            let html = '';
            
            if (tool.description) {
                html += `<p class="tool-description">${tool.description}</p>`;
            }

            tool.parameters.forEach(param => {
                const isRequired = param.required === true;
                const requiredMark = isRequired ? '<span class="field-required">*</span>' : '';
                
                html += `<div class="dialog-form-field">`;
                html += `<label>${param.name}${requiredMark}</label>`;
                
                if (param.type === 'enum' && param.options) {
                    // 🟢 枚举类型渲染为下拉框
                    html += `<select id="param-${param.name}" class="vscode-select" ${isRequired ? 'required' : ''}>`;
                    param.options.forEach(opt => {
                        const selected = opt.value === param.defaultValue ? 'selected' : '';
                        html += `<option value="${opt.value}" ${selected}>${opt.label}</option>`;
                    });
                    html += `</select>`;
                } else if (param.type === 'boolean') {
                    html += `<vscode-checkbox id="param-${param.name}">${param.description || ''}</vscode-checkbox>`;
                } else if (param.type === 'number') {
                    html += `<vscode-text-field 
                        id="param-${param.name}" 
                        type="number" 
                        placeholder="${param.description || ''}"
                        ${isRequired ? 'required' : ''}
                    ></vscode-text-field>`;
                } else if (param.type === 'text' || param.type === 'string') {
                    html += `<vscode-text-area 
                        id="param-${param.name}" 
                        rows="4"
                        placeholder="${param.description || ''}"
                        ${isRequired ? 'required' : ''}
                    ></vscode-text-area>`;
                } else {
                    // 默认文本输入
                    html += `<vscode-text-field 
                        id="param-${param.name}" 
                        placeholder="${param.description || ''}"
                        ${isRequired ? 'required' : ''}
                    ></vscode-text-field>`;
                }
                
                if (param.description && param.type !== 'boolean') {
                    html += `<div class="field-description">${param.description}</div>`;
                }
                
                html += `</div>`;
            });

            return html;
        }

        /**
         * 收集参数值
         * @private
         */
        _collectParameters(tool, dialogInstance) {
            const args = {};
            const dialogElement = dialogInstance.getElement();
            
            if (!dialogElement || !tool.parameters) return args;

            tool.parameters.forEach(param => {
                const input = dialogElement.querySelector(`#param-${param.name}`);
                if (!input) return;

                if (param.type === 'enum') {
                    // 🟢 下拉框直接取value
                    args[param.name] = input.value;
                } else if (param.type === 'boolean') {
                    args[param.name] = input.checked || false;
                } else if (param.type === 'number') {
                    const value = input.value;
                    args[param.name] = value ? Number(value) : undefined;
                } else {
                    args[param.name] = input.value || '';
                }
            });

            return args;
        }

        /**
         * 验证参数
         * @private
         */
        _validateParameters(tool, args) {
            if (!tool.parameters) {
                return { valid: true };
            }

            for (const param of tool.parameters) {
                if (param.required) {
                    const value = args[param.name];
                    if (value === undefined || value === null || value === '') {
                        return {
                            valid: false,
                            message: `参数 "${param.name}" 是必填项`
                        };
                    }
                }
            }

            return { valid: true };
        }

        /**
         * 执行工具
         * @private
         */
        _executeTool(toolId, toolName, args) {
            if (this.onExecute) {
                this.onExecute(toolId, toolName, args);
            }
        }
    }

    window.ToolListView = ToolListView;
})();
